# coding=utf-8
import paramiko
from flask import Flask, jsonify,send_from_directory
from flask import render_template
from flask import request, session, json
import os,time,uuid,datetime
import redis
from flask import redirect
from flask import url_for
from model.check_login import is_existed, exist_user, is_null
from model.check_regist import add_user
from model.check_mysqlmgr import show_dbs, show_tables, show_conf, newdbs, deldbs
from model.ssh import paramiko_GKG, add_cron, list_cron, add_it, get_uid, list_servers, list_assets, list_accounts, \
    del_servers
from templates.config import conn
# k8s
from kubernetes import client, config
# config.kube_config.load_kube_config(config_file = 'D:\PG\config')
# v1 = client.CoreV1Api()
from model.check_k8s import k8sCoreV1Api, k8sAppsV1Api
from model.check_k9s import k8sapi

from model.yml import hyaml
from paramiko import *
# ssh_client
from model.ssh_client import ssh_client

conn_pool = redis.ConnectionPool(host='223.247.189.9', port=6379, db=0, password='123456',decode_responses=True)

app = Flask(__name__)
app.config["SECRET_KEY"] = 'TPmi4aLWRbyVq8zu9v82dWYW1'


# #登录模块
# @app.route("/login",methods=['GET','POST'])
# def login():
#   if request.method == "GET":
#     return render_template('login.html')
#   else:
#     name = request.form.get("user")
#     pwd = request.form.get("pwd")
#     if name =="blc" and pwd == '123456':
#         return '你好呀'
#     else:
#       return "密码错误了"
@app.route('/',methods=["GET"])
def ops():
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        # cur = conn.cursor()
        # # get annual sales rank
        # sql = "select asset,num from blc.echarts"
        # cur.execute(sql)
        # content = cur.fetchall()
        # xdays = []
        # jsonData = {}
        # yvalues = []
        # for data in content:
        #   xdays.append(data[0])
        #   yvalues.append(data[1])
        #   jsonData['xdays'] = xdays
        #   jsonData['yvalues'] = yvalues
        # j = json.dumps(jsonData)
        # cur.close()
        # conn.close()
        # return (j)
        Address = {'cicd': 4, '容器': 159, 'DB': 25, '架构': 117, 'Linux': 800}
        Types = {'Linux': 10, '架构': 5, 'DB': 8, '容器': 4, 'cicd': 4, '开发': 2}
        return render_template('opsbak.html', username=uid,data=json.dumps(Address),data1=json.dumps(Types))


# 登录模块
@app.route('/home')
def index():
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        return render_template('home.html', username=uid)


@app.route('/welcom')
def welcom():
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        return render_template('welcome.html', username=uid)


@app.route('/user_login', methods=['GET', 'POST'])
def user_login():
    if request.method == 'POST':  # 注册发送的请求为POST请求
        #request获取前端用户提交的用户名、密码值
        username = request.form['username']
        password = request.form['password']
        #传值给is_null()判断函数，判断用户输入是否为空，如果为空，强制跳到登录页，提示：账号和密码是必填
        if is_null(username, password):
            login_massage = "温馨提示：账号和密码是必填"
            return render_template('login2.html', message=login_massage)
        #如果存在，传值给is_existed()处理，判断用户名和密码和数据库一致，则转跳到ops.html主页
        elif is_existed(username, password):
            #如果用户名密码ok，则把用户名写入session保存，保持登录
            session['userinfo'] = username
            #return render_template('ops.html', username=username)
            return redirect(url_for('ops',username=username))
        #如果用户存在，传值给exist_user()函数判断用户密码是否正确，如果不正确，则强制转跳登录页并提示密码错误
        elif exist_user(username):
            login_massage = "提示：密码错误，请输入正确密码"
            return render_template('login2.html', message=login_massage)
        #否则，用户不存在
        else:
            login_massage = "不存在该用户"
            return render_template('login2.html', message=login_massage)
    #如果是get请求，返回页面给用户，让用户进行登录操作。
    return render_template('login2.html')


# 退出
@app.route("/logout", methods=["GET"])
def logout():
    session.clear()
    # return "退出成功！"
    return redirect(url_for('user_login'))


@app.route("/regiser", methods=["GET", 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        if is_null(username, password):
            login_massage = "温馨提示：账号和密码是必填"
            return render_template('register1.html', message=login_massage)
        elif exist_user(username):
            return redirect(url_for('user_login'))
        else:
            # add_user(request.form['username'], request.form['password'])
            add_user(username, password)
            return render_template('login2.html', username=username)
    return render_template('register1.html')


# @app.before_request
# def before_user():
#     if 'username' in session:
#         return '已登录'
#         pass
#     else:
#         return '未登录'
# redis操作部分
@app.route('/redis')
def hello_world():
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        return render_template('index.html', username=uid)


@app.route('/find')
def find():
    uid = session.get('userinfo')
    print(uid)
    if not uid:
        return redirect('/user_login')
    else:
        return render_template('redis.html', username=uid)


@app.route('/submit', methods=['POST'])
def insert_data():
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        key = request.form.get("keys")
        values = request.form.get("values")

        r = redis.Redis(connection_pool=conn_pool)

        status = 'Success!'

        try:

            print(key)
            print(values)
            r.set(key, values)
            return "inserted ok"
        except Exception as err:

            status = str(err)
            # return render_template('index.html', status=status)
            return "ok"


@app.route('/show', methods=['POST'])
def show(value=None):
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        a = request.form.get("keys")

        r = redis.Redis(connection_pool=conn_pool)

        value = r.get(a)
        print(value)
        print(type(value))
        return render_template('show.html', value=value)


# mysql
@app.route('/hard')
def hard():
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        content = list_servers()
        content2 = list_assets()
        content3 = list_accounts()
        print(content)
        print(content2)
        return render_template('hard1.html',  content2=content2,content3=content3, content=content, username=uid)

@app.route('/delservers/<id>')
def delservers(id):
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        del_servers(id)
        return redirect(url_for('hard'))

# webssh
@app.route('/webssh')
def webssh():
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        return render_template('webssh1.html', username=uid)


# k8s管理
@app.route('/k8s')
def k8s():
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        config_file = 'kubeconfig.yaml'
        test = k8sAppsV1Api(config_file)
        test1 = k8sCoreV1Api(config_file)
        list_deploment = test.list_deployment()
        list_node = test1.list_nodes()
        list_namespace = test1.list_namespace()
        # 从k9s获取pods
        myk8s = k8sapi()
        pod = myk8s.pods()
        service = myk8s.services()
        print(pod)
        print(service)
        print(type(pod))
        print(list_namespace)
        print(list_deploment)
        print(type(list_node))
        print(type(service))
        for info in list_node:
            print(info)
        for dep in list_deploment:
            print(dep)
        for svc in service:
            for s in svc:
                print(s)

        return render_template('k8sinfo1.html', info=info, dep=list_deploment, pod=pod, ns=list_namespace, username=uid,
                               svc=service)


@app.route('/k9s')
def k9s():
    myk8s = k8sapi()
    myk8s.pods()
    myk8s.namespaces()
    myk8s.services()
    return "success"


@app.route('/deploy')
def deploy():
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        return render_template('deploy.html', username=uid)


# 生成yaml文件
@app.route('/new_deploy', methods=['POST', 'GET'])
def new_deploy():
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        if request.method == 'POST':
            namespace = request.form.get('namespace')
            appname = request.form.get('appname')
            label = request.form.get('label')
            repl = request.form.get('repl')
            matchlabel = request.form.get('matchlabel')
            images = request.form.get('images')
            port = request.form.get('port')
            rmem = request.form.get('rmem')
            rcpu = request.form.get('rcpu')
            lmem = request.form.get('lmem')
            lcpu = request.form.get('lcpu')
            command = request.form.get('command')
            # apiData = {
            #   "namespace": namespace,
            #   "app" : appname,
            #   "label": label,
            #   "mathlabel": matchlabel,
            #   "name": appname,
            #   "image": images,
            #   "port": port,
            #   "command": command,
            #   "rmem": rmem,
            #   "rcpu": rcpu,
            #   "lmem": lmem,
            #   "lcpu": lcpu
            # }
            apiData = {
                "apiVersion": "Apps/v1",
                "kind": "Deployment",
                "metadata": {
                    "name": appname,
                    "labels": {
                        "name": label
                    }
                },
                "spec": {
                    "replicas": repl,
                    "selector": {
                        "matchLabels": {
                            "name": matchlabel
                        }
                    },
                    "strategy": {
                        "rollingUpdate": {
                            "maxSurge": 3,
                            "maxUnavailable": 3
                        },
                        "type": "RollingUpdate"
                    },
                    "template": {
                        "metadata": {
                            "labels": {
                                "name": label
                            }
                        },
                        "spec": {
                            "containers": "",
                            "0": {
                                "name": appname,
                                "image": images,
                                "imagePullPolicy": "IfNotPresent",
                                "resources": {
                                    "requests": {
                                        "cpu": rmem,
                                        "memory": rcpu
                                    },
                                    "limits": {
                                        "cpu": lmem,
                                        "memory": lcpu
                                    }
                                },
                                "livenessProbe": {
                                    "httpGet": {
                                        "path": "/",
                                        "port": port
                                    },
                                    "initialDelaySeconds": 15,
                                    "timeoutSeconds": 3
                                },
                                "readinessProbe": {
                                    "httpGet": {
                                        "path": "/",
                                        "port": port
                                    },
                                    "initialDelaySeconds": 10,
                                    "timeoutSeconds": 3
                                },
                                "env": "",
                                "0": {
                                    "name": "cby",
                                    "value": "chenby"
                                },
                                "ports": "",
                                "1": {
                                    "containerPort": port
                                },
                                "volumeMounts": "",
                                "2": {
                                    "mountPath": "/usr/share/nginx/html/",
                                    "name": "data"
                                }
                            },
                            "volumes": "",
                            "1": {
                                "name": "data",
                                "hostPath": {
                                    "path": "/html/",
                                    "type": "Directory"
                                }
                            },
                            "hostAliases": "",
                            "2": {
                                "ip": "192.168.1.1",
                                "hostnames": "",
                                "0": "cby",
                                "1": "cby.chenby.cn"
                            },
                            "3": {
                                "ip": "192.168.1.10",
                                "hostnames": "",
                                "0": "chenby",
                                "1": "chenby.chenby.cn"
                            }
                        }
                    }
                }
            }

            myyaml = hyaml()
            myyaml.create_yml(appname + '.yaml', apiData)
            return "done"
        else:
            return render_template('create_yml1.html', username=uid)


# monitor
@app.route('/monitor')
def monitor():
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        return render_template('monitor.html', username=uid)


# scheduler
@app.route('/cron', methods=['GET', 'POST'])
def cron():
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        if request.method == 'POST':
            name = request.form.get('crontab')
            cmd = request.form.get('cmd')
            host = request.form.get('host')
            cmdstr = name + '' + cmd
            cmdstr = str(cmdstr)
            laststr = "echo '%s' >>/var/spool/cron/root" % (cmdstr)
            print(laststr)
            result = paramiko_GKG(host, laststr)
            add_cron(host, cmdstr)
            result = list_cron()
            print(result)
            return render_template('cron.html', username=uid, result=result)
        else:
            result = list_cron()
            print(result)
            return render_template('cron.html', username=uid,result=result)


# ssh
@app.route('/mssh', methods=['POST', 'GET'])
def mssh():
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        if request.method == 'GET':
            return render_template('mssh1.html', username=uid)
        else:
            sshclient = paramiko.SSHClient
            ip_list = request.form.getlist('like1')
            print(ip_list)
            # username =  request.form.get('username')
            # pwd =  request.form.get('password')
            cmd = request.form['cmd']
            print(cmd)
            for host in ip_list:
                print(host)
                # sshclient.sshClient(host, 22, username, pwd, cmd)
                return render_template('mssh1.html', username=uid)


##mysql管理
@app.route('/mysqlmgr', methods=['POST', 'GET'])
def mysqlmgr():
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        if request.method == 'GET':
            cdb = "use blc"
            dbs = show_dbs()
            for db in dbs:
                print(db)
            tbs = show_tables(cdb)
            for tb in tbs:
                print(tb)
            mconf = show_conf()
            for conf in mconf:
                print(conf)
            print(type(dbs))
            print(type(tbs))
            return render_template('mysql.html', username=uid, dbs=dbs, mconf=mconf)
        else:
            return "ok"


@app.route('/select', methods=['POST', 'GET'])
def select():
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        if request.method == 'GET':
            cdb = "use blc"
            dbs = show_dbs()
            for db in dbs:
                print(db)
            tbs = show_tables(cdb)
            for tb in tbs:
                print(tb)
            mconf = show_conf()
            for conf in mconf:
                print(conf)
            print(type(dbs))
            print(type(tbs))
            return render_template('mysql.html', username=uid, dbs=dbs, mconf=mconf)
        else:
            dbs = show_dbs()
            mconf = show_conf()
            cdb = request.form.get('modules')
            print(cdb)
            cdb = "use"" " + cdb
            print(cdb)
            tbs = show_tables(cdb)
            print(tbs)
            for t in tbs:
                print(t[0])
            return render_template('select.html', username=uid, dbs=dbs, mconf=mconf, tbs=tbs)


@app.route('/userlist',methods=['POST', 'GET'] )
def userlist():
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        if request.method == 'GET':
            conn.ping(reconnect=True)
            cur = conn.cursor()
            # get annual sales rank
            sql = "select * from userinfo"
            cur.execute(sql)
            content = cur.fetchall()
            print(type(content))
            for us in content:
                print(type(us))
            return render_template('userlist.html', username=uid, userlist=content)
        else:
            name = request.form.get('username')
            print(name)
            cur = conn.cursor()
            # get annual sales rank
            sql = "select * from userinfo where name like '%{}%'".format(name)
            cur.execute(sql)
            content = cur.fetchall()
            print(type(content))
            for us in content:
                print(type(us))
            return render_template('userlist.html', username=uid, userlist=content)


@app.route('/auser')
def auser():
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        return render_template('add_user.html', username=uid)
@app.route('/addit',methods=['POST', 'GET'])
def addit():
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        if request.method == 'GET':
            return render_template('add_it.html', username=uid)
        else:
            host = request.form.get('host')
            ip = request.form.get('ip')
            stype = request.form.get('type')
            zone = request.form.get('zone')

            resource = request.form.get('resource')
            print(host)
            print(zone)
            add_it(host, ip, stype, zone, resource)
            return "add done!"

@app.route('/edit_user', methods=["GET", 'POST'])
def edit_user():
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        if request.method == 'POST':
            name = request.form.get("username")
            phone = request.form.get("phone")
            email = request.form.get("email")
            role = request.form.get("role")
            zhiye = request.form.get("zhiye")
            print(name)
            print(phone)
            print(email)
            print(role)
            print(zhiye)
            uid = get_uid(uid)
            now = datetime.datetime.now()
            today = now.strftime("%Y-%m-%d %H:%M:%S")
            cur = conn.cursor()
            sql = "insert into userinfo values('%s','%s','%s','%s','%s','%s','%s')" % (
                uid, name, phone, email, role, zhiye, today)
            cur.execute(sql)
            result = cur.fetchall()
            # result=result[0][0]
            conn.commit()  # 对数据库内容有改变，需要commit()
            return "done"
        else:
            return render_template('edit_user.html', username=uid)


@app.route('/userinfo')
def userinfo():
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        conn.ping(reconnect=True)
        cur = conn.cursor()
        # get annual sales rank
        myid=get_uid(uid)
        print(uid)
        sql = 'select * from userinfo where uid="%s"'
        sql = sql % (myid)
        print(sql)
        cur.execute(sql)
        content = cur.fetchall()
        print(type(content))
        return render_template('userinfo.html', username=uid, content=content)


@app.route('/cicd')
def cicd():
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        return render_template('cicd.html', username=uid)


# @app.route('/upload', methods=['GET', 'POST'])
# def upload():
#   uid = session.get('userinfo')
#   if not uid:
#     return redirect('/user_login')
#   else:
# 	f = request.files.get('file')
# 	f.save('./{}'.format(f.filename))
@app.route('/error')
def error():
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        return render_template('error.html', username=uid)


@app.route('/test001')
def test001():
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        return render_template('test001.html', username=uid)




#共享文件服务器
# 文件共享
@app.route('/file-upload', methods=['GET', 'POST'])
def file_upload():
    if request.method == 'POST':
        file = request.files['file']
        project_path = r'C:\Users\zhangbaolong\PycharmProjects\midware\static\upload'
        file_path = project_path + '\\' + file.filename
        print('文件保存路径:', file_path)
        file.save(file_path)
        return jsonify({'code': 0, 'msg': '上传成功', 'data': {'src': file_path}})
    else:
        return render_template('file.html')


# 共享文件共享
# 共享文件夹的根目录
rootdir = r'C:\Users\zhangbaolong\PycharmProjects\midware\static\upload'


@app.route('/doc/')
@app.route('/doc/<subdir>/')
def document(subdir=''):
    if subdir == '':
        # 名字为空，切换到根目录
        os.chdir(rootdir)
    else:
        print(subdir)
        fullname = rootdir + os.sep + subdir
        print(fullname)
        #  如果是文件，则下载
        if os.path.isfile(fullname):
            return redirect(url_for('downloader', fullname=fullname))
        #  如果是目录，切换到该目录下面
        else:
            os.chdir(fullname)
    current_dir = os.getcwd()
    current_list = os.listdir(current_dir)
    contents = []
    for i in sorted(current_list):
        fullpath = current_dir + os.sep + i
        # 如果是目录，在后面添加一个sep
        if os.path.isdir(fullpath):
            extra = os.sep
        else:
            extra = ''
        content = {}
        content['filename'] = i + extra
        content['mtime'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(os.stat(fullpath).st_mtime))
        content['size'] = str(round(os.path.getsize(fullpath) / 1024)) + 'k'
        contents.append(content)
    return render_template('files.html', contents=contents, subdir=subdir, ossep=os.sep)


@app.route('/download/<fullname>')
def downloader(fullname):
    print(fullname)
    filename = fullname.split(os.sep)[-1]
    dirpath = fullname[:-len(filename)]
    return send_from_directory(dirpath, filename, as_attachment=True)

#定义一个新建db的路由，如果url路径匹配到/newdb，则被转进入到newdb()这个处理逻辑函数里
@app.route('/newdb',methods=['POST', 'GET'])
def newdb():
    #判断用户是否登录，获取到session即：uid，然后判断是否存在，不存在则强制转跳到user_login登录模块进行登录
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        #如果用户已经登录，如果是get请求，则返回新建数据库页面
        if request.method == 'GET':
            return render_template('newdb.html')
        else:
            #如果是post提交请求，则使用request方法获取前端db值，如db（用户输入的新库名）
            db = request.form.get('db')
            #调试打印获取的库名
            print(db)
            #把库名传如函数：newdbs()进行新建库的逻辑
            newdbs(db)
            #完成后，返回done提示
            return "done"

@app.route('/deldb/<db>')
def deldb(db):
    uid = session.get('userinfo')
    if not uid:
        return redirect('/user_login')
    else:
        deldbs(db)
        return redirect(url_for('mysqlmgr'))


if __name__ == '__main__':
    app.run(host='0.0.0.0', port='8000', debug=True)
